import pymysql
import time
import subprocess

#日志采集
#注意：日志会备份到Mysql，因此保证MySQL可用

def collect_metrics():
    # 采集CPU、内存、磁盘使用率
    cpu = subprocess.check_output("top -bn1 | grep 'Cpu(s)' | awk '{print $2}'", shell=True)  or '0'
    mem = subprocess.check_output("free -m | grep Mem | awk '{print $3/$2 * 100}'", shell=True)  or '0'
    disk = subprocess.check_output("df -h | grep /dev/sda1 | awk '{print $5}'", shell=True)  or '0'
    return cpu.strip(), mem.strip(), disk.strip()

def save_to_mysql():
    db = pymysql.connect(
        host="192.168.0.104",
        user="root",
        passwd="123123",
        db="python_monitor"
    )
    cursor = db.cursor()

    cpu, mem, disk = collect_metrics()    

    try:
        cpu = float(cpu) if cpu else 0.0
    except ValueError:
        cpu = 0.0
    try:
        mem = float(mem) if mem else 0.0
    except ValueError:
        mem = 0.0
    try:
        disk = float(disk) if disk else 0.0
    except ValueError:
        disk = 0.0

    print(f"cpu: {cpu}, memory: {mem}, disk: {disk}")

    cursor.execute("INSERT INTO metrics (cpu, memory, disk) VALUES (%s, %s, %s)", (cpu, mem, disk))

    db.commit()

    db.close()

# # 定时任务（每5分钟执行一次）
# while True:
#     save_to_mysql()
#     time.sleep(300)